package com.cloud.gateway;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
// @Order(0) // 顺序注解，指定过滤器在过滤器链中的顺序，值越小优先级越高，也可以通过实现接口重写方法指定顺序
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> queryParams = request.getQueryParams();

        // 2. 获取参数中的目标参数
        String auth = queryParams.getFirst("authorization");

        // 3. 判断目标参数值是否与预期一致
        if ("admin".equals(auth)) {
            // 4. 一致，放行
            return chain.filter(exchange);
        }

        // 5. 不一致，拦截
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); // 设置状态码，这里401代表未登录
        return exchange.getResponse().setComplete(); // 拦截
    }

    /**
     * 指定过滤器在过滤器链中的顺序，也可以通过注解指定
     * @return
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
